package com.xiachufang.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiachufang.app.common.Res;
import com.xiachufang.app.entity.LoopAd;
import com.xiachufang.app.service.LoopAdService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/loopAd")
public class LoopAdController {

    @Resource
    private LoopAdService loopAdService;

    /**
     * 先更新 再新增
     *
     * @param loopAd
     * @return
     */
    @PostMapping
    public Res<?> save(@RequestBody LoopAd loopAd) {
        boolean update = loopAdService.updateById(loopAd);
        if (!update) {
            loopAdService.save(loopAd);
        }
        return Res.success();
    }

    @DeleteMapping("/{id}")
    public Res<?> delete(@PathVariable Integer id) {
        loopAdService.removeById(id);
        return Res.success();
    }

    @GetMapping
    public Res<?> all() {
        return Res.success(loopAdService.list());
    }


    /**
     * 分页查询接口
     *
     * @param pageNum  页码
     * @param pageSize 每页个数
     * @param name     模糊查询关键字
     * @return page对象
     */
    @GetMapping("/page")
    public Res<?> page(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false, defaultValue = "") String name) {
        QueryWrapper<LoopAd> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        return Res.success(loopAdService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}

